import java.util.Arrays;

public class TableData {

    private RowData[] rowDatas = new RowData[0];

    public void addCell(CellData cellData) {
        int row = cellData.getPosRow();
        if (rowDatas.length <= row) {
            rowDatas = Arrays.copyOf(rowDatas, row + 1, RowData[].class);
            RowData rowData = new RowData(row);
            rowData.addCell(cellData);
            rowDatas[row] = rowData;
        }
        if (rowDatas[row] == null) {
            RowData rowData = new RowData(row);
            rowData.addCell(cellData);
            rowDatas[row] = rowData;
        } else {
            rowDatas[row].addCell(cellData);
        }
    }


    public void printTable() {
        for (RowData rowData : rowDatas) {
            rowData.printRow();
        }
    }

    public RowData[] getRowDatas() {
        return rowDatas;
    }

    public String toHTML() {
        StringBuffer buffer = new StringBuffer();

        buffer.append("<table border=\"1\">");
        for (RowData rowData : rowDatas) {
            buffer.append("<tr>");
            for (CellData cellData : rowData.getCellDatas()) {
                buffer.append(generateHtml(cellData));
            }
            buffer.append("</tr>");
        }
        buffer.append("</table>");
        return buffer.toString();
    }

    private String generateHtml(CellData cellData) {
        if (cellData == null) {
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append("<td");
        if (cellData.getRowSpan() > 0) {
            buffer.append(" rowSpan=");
            buffer.append("\"");
            buffer.append(cellData.getRowSpan());
            buffer.append("\"");
        }
        buffer.append(">");
        buffer.append(cellData.getValue());
        buffer.append("</td>");
        return buffer.toString();
    }

}
